package com.bluishoul.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
/**
 * 文件存储，仅限存储字符串
 * @author jack
 *
 */
public class FileService {
	public static final String EXT = ".json";

	/**
	 * 添加文件
	 * 
	 * @param domin
	 * @param key
	 * @param value
	 * @return
	 * @throws IOException
	 */
	public static boolean add(String domin, String name, String value)
			throws IOException {
		File dir = new File(domin);
		if (!dir.isDirectory())
			dir.mkdirs();
		File file = new File(domin + name + EXT);
		FileUtils.writeStringToFile(file, value);
		return true;
	}

	/**
	 * 通过key和domin拿到value
	 * 
	 * @param domin
	 * @param key
	 * @return
	 * @throws IOException
	 */
	public static String getValueByKey(String domin, String name)
			throws IOException {
		File file = new File(domin + name + EXT);
		return FileUtils.readFileToString(file);
	}

	/**
	 * 通过domin拿到所有的values
	 * 
	 * @return
	 * @throws IOException
	 */
	public static List<String> getValueListByDomin(String domin)
			throws IOException {
		Iterator<File> it = FileUtils.iterateFiles(new File(domin), null, true);
		List<String> value_list = new ArrayList<String>();
		while (it.hasNext()) {
			File f = (File) it.next();
			value_list.add(FileUtils.readFileToString(f));
		}
		return value_list;
	}

	/**
	 * 拿到所有的values
	 * 
	 * @return
	 */
	public static List<String> getAllValues() {
		Iterator<File> it = FileUtils.iterateFiles(new File(""), null, true);
		List<String> key_list = new ArrayList<String>();
		while (it.hasNext()) {
			File f = (File) it.next();
			key_list.add(FilenameUtils.getBaseName(f.getName()));
		}
		return key_list;
	}

	/**
	 * 通过domin拿到key列表
	 * 
	 * @param domin
	 * @return
	 */
	public static List<String> getNameListByDomin(String domin) {
		Iterator<File> it = FileUtils.iterateFiles(new File(domin), null, true);
		List<String> name_list = new ArrayList<String>();
		while (it.hasNext()) {
			File f = (File) it.next();
			name_list.add(FilenameUtils.getBaseName(f.getName()));
		}
		return name_list;
	}

	/**
	 * 判断文件是否存在
	 */
	public static boolean isFileExist(String domin, String name) {
		return new File(domin + name + EXT).exists();
	}
}
